import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/**
 *Created by Jcy
 *on 2021/10/19
 */

///通常是和 viewpager 联合使用  ， 类似于Android 中的 fragment
/// 不过生命周期 还需要在容器父类中根据tab切换来完善
abstract class BaseViewPageWidget extends StatefulWidget {
  BaseViewPageWidgetState? baseWidgetState;

  @override
  BaseViewPageWidgetState createState() {
    baseWidgetState = getState();
    return baseWidgetState!;
  }

  BaseViewPageWidgetState getState();

  String getStateName() {
    return baseWidgetState!.getClassName();
  }
}

abstract class BaseViewPageWidgetState<T extends BaseViewPageWidget>
    extends State<T> with AutomaticKeepAliveClientMixin {
  //平台信息
//  bool isAndroid = Platform.isAndroid;
  @override
  bool get wantKeepAlive => false;

  bool _isErrorWidgetShow = false; //错误信息是否显示

  Color _appBarColor = Colors.red;

  String _errorContentMesage = "网络错误啦~~~";

  String _errImgPath = "images/start_image.jpg";

  bool _isLoadingWidgetShow = false;

  bool _isEmptyWidgetVisible = false;

  String _emptyWidgetContent = "暂无数据~";

  String _emptyImgPath = "images/start_image.jpg"; //自己根据需求变更

  FontWeight _fontWidget = FontWeight.w600; //错误页面和空页面的字体粗度


  @override
  void initState() {
    onCreate();
    onResume();
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: _appBarColor,
        automaticallyImplyLeading: false,
        brightness: Brightness.light,
        elevation: 0,
        title: setAppBar(),
      ),
      body: _getBaseView(context),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    onDestory();
    super.dispose();
  }

  void log(String content) {
    print(getClassName() + "-innerWidget-----:" + content);
  }

  ///页面被覆盖,暂停
  void onPause();

  ///相当于onResume, 只要页面来到栈顶， 都会调用此方法，网络请求可以放在这个方法
  void onResume();

  ///返回UI控件 相当于setContentView()
  Widget buildWidget(BuildContext context);

  ///自定义appbar样式
  Widget setAppBar();

  ///初始化一些变量 相当于 onCreate ， 放一下 初始化数据操作
  void onCreate();

  ///页面注销方法
  void onDestory() {
    log("destory");
  }

  Widget _getBaseView(BuildContext context) {
    return Container(
      color: Colors.white, //背景颜色，可自己变更
      child: Stack(
        children: <Widget>[
          buildWidget(context),
          _getBaseErrorWidget(),
          _getBaseEmptyWidget(),
          _getBassLoadingWidget(),
        ],
      ),
    );
  }

  ///暴露的错误页面方法，可以自己重写定制
  Widget getErrorWidget() {
    return Container(
      //错误页面中心可以自己调整
      padding: EdgeInsets.fromLTRB(0, 0, 0, 200),
      color: Colors.white,
      width: double.infinity,
      height: double.infinity,
      child: Center(
        child: InkWell(
          onTap: onClickErrorWidget,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                onTap: (){
                  onCreate();
                },
                child: Image(
                  image: AssetImage(_errImgPath),
                  width: 150,
                  height: 150,
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Text(_errorContentMesage,
                    style: TextStyle(
                      fontWeight: _fontWidget,
                    )),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget getLoadingWidget() {
    return Container(
      //错误页面中心可以自己调整
      padding: EdgeInsets.fromLTRB(0, 0, 0, 100),
      color: Colors.black12,
      width: double.infinity,
      height: double.infinity,
      child: Center(
        child:
            // 圆形进度条
            new CircularProgressIndicator(
          strokeWidth: 4.0,
          backgroundColor: Colors.blue,
          // value: 0.2,
          valueColor: new AlwaysStoppedAnimation<Color>(_appBarColor),
        ),

//        Container(
//          alignment: Alignment.center,
//          color: Colors.white70,
//          width: 200,
//          height: 200,
//          child: Text("你懂么？~~~"),
//        )
//
      ),
    );
  }

  Widget _getBaseErrorWidget() {
    return Offstage(
      offstage: !_isErrorWidgetShow,
      child: getErrorWidget(),
    );
  }

  Widget _getBassLoadingWidget() {
    return Offstage(
      offstage: !_isLoadingWidgetShow,
      child: getLoadingWidget(),
    );
  }

  Widget _getBaseEmptyWidget() {
    return Offstage(
      offstage: !_isEmptyWidgetVisible,
      child: getEmptyWidget(),
    );
  }

  Widget getEmptyWidget() {
    return Container(
      //错误页面中心可以自己调整
      padding: EdgeInsets.fromLTRB(0, 0, 0, 200),
      color: Colors.white,
      width: double.infinity,
      height: double.infinity,
      child: Center(
        child: Container(
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                onTap: (){
                  onCreate();
                },
                child: Image(
                  // color: Colors.black12,
                  image: AssetImage(_emptyImgPath),
                  width: 150,
                  height: 150,
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Text(_emptyWidgetContent,
                    style: TextStyle(
                      fontWeight: _fontWidget,
                    )),
              )
            ],
          ),
        ),
      ),
    );
  }

  ///关闭最后一个 flutter 页面 ， 如果是原生跳过来的则回到原生，否则关闭app
  void finishDartPageOrApp() {
    SystemNavigator.pop();
  }

  ///点击错误页面后展示内容
  void onClickErrorWidget() {
    onResume(); //此处 默认onResume 就是 调用网络请求，
  }

  ///设置错误提示信息
  void setErrorContent(String content) {
    if (content != null) {
      setState(() {
        _errorContentMesage = content;
      });
    }
  }

  ///设置错误页面显示或者隐藏
  void setErrorWidgetVisible(bool isVisible) {
    setState(() {
      if (isVisible) {
        //如果可见 说明 空页面要关闭啦
        _isEmptyWidgetVisible = false;
      }
      // 不管如何loading页面要关闭啦，
      _isLoadingWidgetShow = false;
      _isErrorWidgetShow = isVisible;
    });
  }

  ///设置appbar颜色
  void setAppBarColor(Color color) {
    setState(() {
      _appBarColor = color;
    });
  }

  ///设置空页面显示或者隐藏
  void setEmptyWidgetVisible(bool isVisible) {
    setState(() {
      if (isVisible) {
        //如果可见 说明 错误页面要关闭啦
        _isErrorWidgetShow = false;
      }

      // 不管如何loading页面要关闭啦，
      _isLoadingWidgetShow = false;
      _isEmptyWidgetVisible = isVisible;
    });
  }

  void setLoadingWidgetVisible(bool isVisible) {
    setState(() {
      _isLoadingWidgetShow = isVisible;
    });
  }

  ///设置空页面内容
  void setEmptyWidgetContent(String content) {
    if (content != null) {
      setState(() {
        _emptyWidgetContent = content;
      });
    }
  }

  ///设置错误页面图片
  void setErrorImage(String imagePath) {
    if (imagePath != null) {
      setState(() {
        _errImgPath = imagePath;
      });
    }
  }

  ///设置空页面图片
  void setEmptyImage(String imagePath) {
    if (imagePath != null) {
      setState(() {
        _emptyImgPath = imagePath;
      });
    }
  }

  String getClassName() {
    if (context == null) {
      return '';
    }
    String className = context.toString();
    if (className == null) {
      return '';
    }
    className = className.substring(0, className.indexOf("("));
    return className;
  }
}
